package com.xorcrypt.textmsg;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;



public class XORcryptActivity extends Activity {

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) 
	{
	  if (requestCode == 10600  && resultCode ==-1)
	  {         
	    getContactInfo(intent); 
	  }
	}
  
	@Override

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final TextView encryptedtext =    (TextView) findViewById(R.id.encryptedtext);
        final EditText encryptionkey =    (EditText) findViewById(R.id.encryptionkey);
        final EditText messagetoencrypt = (EditText) findViewById(R.id.messagetoencrypt);
        final TextView readtext = (TextView) findViewById(R.id.readtext);
        final EditText txtphoneNo = (EditText) findViewById(R.id.txtphoneNo);
        final Button cipherbtn = (Button) findViewById(R.id.cipherbtn);
        final Button writebtn = (Button) findViewById(R.id.writebtn);
        final Button receivebtn = (Button) findViewById(R.id.receivebtn);
        final Button sendbtn = (Button) findViewById(R.id.sendbtn);
        final RadioGroup cipherradio = (RadioGroup) findViewById(R.id.cipherradio);
        final TextView cipher01 = (TextView) findViewById(R.id.cipher01);
        
        final Button previousmessage = (Button) findViewById(R.id.previousmessage);
        final Button refreshmessage = (Button) findViewById(R.id.refreshmessage);
        final Button nextmessage = (Button) findViewById(R.id.nextmessage);
        final Button btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
        final Button savekey = (Button) findViewById(R.id.savekey);
        final Button readkey = (Button) findViewById(R.id.readkey);

        final RadioButton ciphernone = (RadioButton) findViewById(R.id.ciphernone);
        final RadioButton cipherabc = (RadioButton) findViewById(R.id.cipherabc);
        final RadioButton cipherxor = (RadioButton) findViewById(R.id.cipherxor);
        final RadioButton cipherpass = (RadioButton) findViewById(R.id.cipherpass);
        
   	    final Uri SMS_INBOX = Uri.parse("content://sms/");
   	    final EditText messagestate = (EditText) findViewById(R.id.messagestate);
        
        txtphoneNo.setOnLongClickListener(new View.OnLongClickListener() {
			
			public boolean onLongClick(View v) {
				int PICK_CONTACT = 10600;
	          	  Intent intentContact = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); 
	        	  startActivityForResult(intentContact, PICK_CONTACT);
				return false;
			}
		});

        savekey.setOnClickListener(new View.OnClickListener() 
        {public void onClick(View v) 
            {writecrypt();}});
        
        readkey.setOnClickListener(new View.OnClickListener() 
        {public void onClick(View v) 
            {readcrypt();}});
        
        
        nextmessage.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {    
           	 Cursor c = getContentResolver().query(SMS_INBOX, new String[] { "person","body","subject" }, null, null, null);         	 
             	 c.moveToFirst();
             	 int messagepos = Integer.parseInt(messagestate.getText().toString());
             	 messagepos = messagepos+1;
             	 
             	 if(messagepos>(c.getCount()-1)){
             		 messagepos = messagepos-1;};
             	 
             	 c.moveToPosition(messagepos);
             	 String blah2 = c.getString(1);
            	 readtext.setText(blah2);
            	 messagestate.setText(String.valueOf(messagepos));
            	 
            	 deciphermessage(encryptionkey.getText().toString(),blah2);
            }
        });
	
        previousmessage.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {    
            	 Cursor c = getContentResolver().query(SMS_INBOX, new String[] { "person","body","subject" }, null, null, null);         	 
         	 c.moveToFirst();
         	 int messagepos = Integer.parseInt(messagestate.getText().toString());
         	 messagepos = messagepos-1;
         	 if(messagepos<0)
         		 messagepos = 0;
         	 c.moveToPosition(messagepos);
         	 String blah2 = c.getString(1);
        	 readtext.setText( blah2);
        	 messagestate.setText(String.valueOf(messagepos));  //my method for global variable
        	 
        	 deciphermessage(encryptionkey.getText().toString(),blah2);
            }
        });
        
        refreshmessage.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {    
            	 Cursor c = getContentResolver().query(SMS_INBOX, new String[] { "person","body","subject" }, null, null, null);         	 
         	 c.moveToFirst();
         	 int messagepos = Integer.parseInt(messagestate.getText().toString());
         	 c.moveToPosition(messagepos);
         	 String blah2 = c.getString(1);
        	 readtext.setText( blah2);
        	 messagestate.setText(String.valueOf(messagepos));  //my method for global variable
        	 deciphermessage(encryptionkey.getText().toString(),blah2);
        	 
            }
        });
        

        btnSendSMS.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {                
                //SmsManager sms = SmsManager.getDefault();
                String recipient = txtphoneNo.getText().toString();
                String msg = encryptedtext.getText().toString();
                if (recipient.length()>0 && msg.length()>0){  
                try{
                	sendSMS(recipient,msg);}
                catch (Exception e) {
                	toasty("Message too long..");
//                	toasty("Error! " + e.toString());
                };
                }
                else
                	toasty("No message or number!");                	
            }
        });
        
        // Make stuff visible and invisible and whatever
        {  // view on startup
        	visiblemenu(1);
            this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);  //make keyboard not auto start 
            if(!(cipherxor.isChecked()||cipherabc.isChecked()||cipherpass.isChecked())){  // make a cipher button auto
            ciphernone.setChecked(true);
            }
            ;}
        
        // STUFF TO DO WHEN CIPHER BUTTON IS SELECTED
        cipherbtn.setOnClickListener(new View.OnClickListener() 
        {public void onClick(View v){        
            	visiblemenu(2);
            }});
       
        // STUFF TO DO WHEN WRITE IS SELECTED
        writebtn.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {         
            visiblemenu(3);
            }});
       
        // STUFF TO DO WHEN SEND BUTTON IS SELECTED
        sendbtn.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {            
 visiblemenu(4);
                      
                      
     
              if(ciphernone.isChecked()){
            	  encryptedtext.setText(messagetoencrypt.getText());
              };
              
if(cipherabc.isChecked()){
	encryptedtext.setText(encryptabc(encryptionkey.getText().toString(),
			messagetoencrypt.getText().toString()));
              };
              
if(cipherpass.isChecked()){         	  
try {
	encryptedtext.setText(encrypt(encryptionkey.getText().toString(),
			messagetoencrypt.getText().toString()));} 
catch (Exception e) {
	e.printStackTrace();
}};
              
if(cipherxor.isChecked()){

	int encposition =1;	
	
	encryptedtext.setText(XORcryptstring(messagetoencrypt.getText().toString(), 
    	encryptionkey.getText().toString(),  encposition));        	  
          };
            }
            });
        
        
        
        // STUFF TO DO WHEN DECRYPT BUTTON IS SELECTED
        receivebtn.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {        
visiblemenu(5);
                      
Cursor c = getContentResolver().query(SMS_INBOX, new String[] { "person","body","subject" }, null, null, null);         	 
 c.moveToFirst();
 int messagepos = Integer.parseInt(messagestate.getText().toString());
 c.moveToPosition(messagepos);
 String blah2 = c.getString(1);
readtext.setText( blah2);
messagestate.setText(String.valueOf(messagepos));  //my method for global variable
deciphermessage(encryptionkey.getText().toString(),blah2);
            }
            });
        
        
        cipherradio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        	public void onCheckedChanged(RadioGroup group, int checkedId) {
              if(ciphernone.isChecked()){
        	  cipher01.setText("No encryption used.");
        	  encryptionkey.setHint("Filling this box does nothing to your text message unless you select a different button on top.");
          };
          
          if(cipherpass.isChecked()){
        	  cipher01.setText("A password is used to generate the encryption.");
        	  encryptionkey.setHint("This password is used as a seed for AES128 bit encryption.");
          };
          if(cipherabc.isChecked()){
        	  cipher01.setText("Every letter corresponds directly to another letter.");
        	  encryptionkey.setHint("abcdefghijklmnopqrstuvwxyz ,.1234567890ABCDEFGHIJKLMNOPQRSTUVXYZ?/|~\\\nFilling in all letters unnecessary but improves security.");          };
          if(cipherxor.isChecked()){
        	  cipher01.setText("Bit by bit encryption.");
        	encryptionkey.setHint("Every bit is encrypted directly bit by bit, using whatever sequence you enter.  Any file that replaces 'xorsettings.dat' can be read as a key.");
          };
        	}});
    }  //close of the onCreate class    
	
	public static String XORcryptstring(String msg, String enckey,  int encposition){
    	// Note:  encposition not yet implemented
    	//couple of quick checks
    	if(enckey.length()==0){
    		 return msg;  //if no key is used, msg is returned
    	}
    	if(msg.length()==0)
    		return "";
    	if(enckey.length()<msg.length()*2){  //ensure the key is long enough, if not, expand the key
    		int expandkey = 2*msg.length()/enckey.length()+1;  //+1 to make sure you always have enough
    		String initialenckey = enckey;
    		for(int i = 0; i<expandkey; ++i){
    			enckey += initialenckey;
    		}
    	}
    	
    	

// Begin encrypting!    	
        String msginhex = toHex(msg);
        
        byte[] b2 = new byte[2*enckey.length()-1];
        
    	try {
    		b2 = toByte(enckey);}
      	catch (Exception e) {
      		enckey = toHex(enckey);
      	}
        
    	byte[] b1 = new byte[msginhex.length()-1];
//    	byte[] b2 = new byte[enckey.length()-1];
    	b1 = toByte(msginhex);
    	b2 = toByte(enckey);
    	
    	
    		
	    byte[] c = new byte[msg.length()];
    	for(int counter = 0; counter<msg.length(); ++counter){
    		 c[counter] = (byte) (b1[counter] ^ b2[counter]);
    	};
        String encryptedmessage = toHex(c);
        
	return encryptedmessage;
	}
	
	
	public static String XORdecryptstring(String enckey, String msg,  int encposition){
		//The fantastic irony of this is that it works in reverse as well.  :)
    	// Note:  encposition not yet implemented
		
    	//couple of quick checks
    	if(enckey.length()==0){
    		 return msg;  //if no key is used, msg is returned
    	}
    	if(msg.length()==0)
    		return "";

    	if(enckey.length()<2*msg.length()){  //ensure the key is long enough, if not, expand the key
    		int expandkey = 2*msg.length()/enckey.length()+1;  //+1 to make sure you always have enough
    		String initialenckey = enckey;
    		for(int i = 0; i<expandkey; ++i){
    			enckey += initialenckey;
    		}}
    	
    		
            String msginhex = toHex(msg);
        	
        	byte[] b1 = new byte[msginhex.length()];
        	byte[] b2 = new byte[2*enckey.length()]; 
        	

            
        	try {
        		b2 = toByte(enckey);}
          	catch (Exception e) {
          		enckey = toHex(enckey);
          	}
          	
          	
        	  	try {
              		b1 = toByte(msg);}
              	catch (Exception e) {
              		return msg;
              	}
        		
        			
    	    byte[] c = new byte[msginhex.length()];
        	for(int counter = 0; counter<msg.length()/2; ++counter){
       		 c[counter] = (byte) (b1[counter] ^ b2[counter]);
       	};
       	   
           String decryptedhexcode = toHex(c);
           String messageout = fromHex(decryptedhexcode);
           
       	   return messageout;
	}
	
	
	private void sendSMS(String phoneNumber, String message)
	    {        
	        String SENT = "SMS_SENT";
	        String DELIVERED = "SMS_DELIVERED";
	 
	        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
	            new Intent(SENT), 0);
	        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
	            new Intent(DELIVERED), 0);
	        //---when the SMS has been sent---
	        registerReceiver(new BroadcastReceiver(){
	            @Override
	            public void onReceive(Context arg0, Intent arg1) {
	                switch (getResultCode())
	                {
	                    case Activity.RESULT_OK:
	                        Toast.makeText(getBaseContext(), "SMS succesfully sent.", 
	                                Toast.LENGTH_SHORT).show();
	                        break;
	                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
	                        Toast.makeText(getBaseContext(), "Generic failure.", 
	                                Toast.LENGTH_SHORT).show();
	                        break;
	                    case SmsManager.RESULT_ERROR_NO_SERVICE:
	                        Toast.makeText(getBaseContext(), "No service.", 
	                                Toast.LENGTH_SHORT).show();
	                        break;
	                    case SmsManager.RESULT_ERROR_NULL_PDU:
	                        Toast.makeText(getBaseContext(), "Null PDU.", 
	                                Toast.LENGTH_SHORT).show();
	                        break;
	                    case SmsManager.RESULT_ERROR_RADIO_OFF:
	                        Toast.makeText(getBaseContext(), "Radio off.", 
	                                Toast.LENGTH_SHORT).show();
	                        break;
	                }
	            }
	        }, new IntentFilter(SENT));
	 
	        //---when the SMS has been delivered---
	        registerReceiver(new BroadcastReceiver(){
	            @Override
	            public void onReceive(Context arg0, Intent arg1) {
	                switch (getResultCode())
	                {
	                    case Activity.RESULT_OK:
	                        Toast.makeText(getBaseContext(), "SMS delivered", 
	                                Toast.LENGTH_SHORT).show();
	                        break;
	                    case Activity.RESULT_CANCELED:
	                        Toast.makeText(getBaseContext(), "SMS not delivered", 
	                                Toast.LENGTH_SHORT).show();
	                        break;                        
	                }
	            }
	        }, new IntentFilter(DELIVERED));        
	 
	        SmsManager sms = SmsManager.getDefault();
	        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);        
	    }



public static String encrypt(String seed, String cleartext) throws Exception {
        byte[] rawKey = getRawKey(seed.getBytes());
        byte[] result = encrypt(rawKey, cleartext.getBytes());
        return toHex(result);
}

public static String decrypt(String seed, String encrypted) throws Exception {
        byte[] rawKey = getRawKey(seed.getBytes());
        byte[] enc = toByte(encrypted);
        byte[] result = decrypt(rawKey, enc);
        return new String(result);
}

private static byte[] getRawKey(byte[] seed) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(seed);
    kgen.init(128, sr); // 192 and 256 bits may not be available
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();
    return raw;
}


private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypted = cipher.doFinal(clear);
        return encrypted;
}

private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    byte[] decrypted = cipher.doFinal(encrypted);
        return decrypted;
}


public static String encryptabc(String charseq, String message) {
	
	if(charseq.length()<30){
		charseq = charseq.toLowerCase();
	    message = message.toLowerCase();	
	};
	
		String codeto = "abcdefghijklmnopqrstuvwxyz ,.1234567890ABCDEFGHIJKLMNOPQRSTUVXYZ?/|~\\\n";
	    
	    char[] cs = new char[charseq.length()];
	    char[] msg = new char[message.length()];
	    char[] result = new char[message.length()];
	    char[] ct = new char[codeto.length()];
	    
		for(int i=0; i<message.length(); i++){
	    msg[i] = message.charAt(i);
		};
		for(int i=0; i<charseq.length(); i++){
		    cs[i] = charseq.charAt(i);
			};
			for(int i=0; i<codeto.length(); i++){
			    ct[i] = codeto.charAt(i);
				};
				
				for(int i=0; i<message.length(); i++){
				for(int j=0; j<charseq.length(); j++){
				if(msg[i]==ct[j]){
					result[i]=cs[j];}
				else{
					if(result[i]==0)
					result[i]=msg[i];
				};
				};
				};
    return String.valueOf(result);
}


public static String decryptabc(String charseq, String message) {
	
	if(charseq.length()<30){
		charseq = charseq.toLowerCase();
	    message = message.toLowerCase();	
	};
	
		String codeto = "abcdefghijklmnopqrstuvwxyz ,.1234567890ABCDEFGHIJKLMNOPQRSTUVXYZ?/|~\\\n";
	    
	    char[] cs = new char[charseq.length()];
	    char[] msg = new char[message.length()];
	    char[] result = new char[message.length()];
	    char[] ct = new char[codeto.length()];
	    
		for(int i=0; i<message.length(); i++){
	    msg[i] = message.charAt(i);
		};
		for(int i=0; i<charseq.length(); i++){
		    cs[i] = charseq.charAt(i);
			};
			for(int i=0; i<codeto.length(); i++){
			    ct[i] = codeto.charAt(i);
				};
				
				for(int i=0; i<message.length(); i++){
				for(int j=0; j<charseq.length(); j++){
				if(msg[i]==cs[j]){
					result[i]=ct[j];}
				else{
					if(result[i]==0)
					result[i]=msg[i];
				};
				};
				};
    return String.valueOf(result);
}




//Save settings
//WriteSettings(this,"setting0, setting1, setting2");
public void WriteSettings(Context context, String data){
    FileOutputStream fOut = null;
    OutputStreamWriter osw = null;
    try{
     fOut = openFileOutput("settings.dat",MODE_PRIVATE);      
     osw = new OutputStreamWriter(fOut);
     osw.write(data);
     osw.flush();
     Toast.makeText(context, "Settings saved",Toast.LENGTH_SHORT).show();
     }
     catch (Exception e) {      
     e.printStackTrace();
     Toast.makeText(context, "Settings not saved",Toast.LENGTH_SHORT).show();
     }

     finally {
        try {
               osw.close();
               fOut.close();
               } catch (IOException e) {
               e.printStackTrace();
               }
     }
}

public void setcipher(int scipher){
	
    final RadioButton ciphernone = (RadioButton) findViewById(R.id.ciphernone);
    final RadioButton cipherabc = (RadioButton) findViewById(R.id.cipherabc);
    final RadioButton cipherpass = (RadioButton) findViewById(R.id.cipherpass);
    final RadioButton cipherxor = (RadioButton) findViewById(R.id.cipherxor);

switch (scipher){
case 0:
case 48: ciphernone.setChecked(true); break;
case 1:
case 49: cipherabc.setChecked(true); break;
case 2:
case 50: cipherpass.setChecked(true); break;
case 3:
case 51: 
default:
	cipherxor.setChecked(true); break;
}
};

public int selectedcipher(){
	
	int selcipher = 0;
    final RadioButton ciphernone = (RadioButton) findViewById(R.id.ciphernone);
    final RadioButton cipherabc = (RadioButton) findViewById(R.id.cipherabc);
    final RadioButton cipherpass = (RadioButton) findViewById(R.id.cipherpass);
    final RadioButton cipherxor = (RadioButton) findViewById(R.id.cipherxor);

    if(ciphernone.isChecked())
    {
    	selcipher = 0;
    }else if(cipherabc.isChecked()){
    	selcipher = 1;
    }else if(cipherpass.isChecked()){
    selcipher = 2;
    }else if(cipherxor.isChecked()){
    	selcipher = 3;
    };

return selcipher;
};


public void writecrypt(){
	
	final EditText encryptionkey =    (EditText) findViewById(R.id.encryptionkey);
	String data = null;
	data = String.valueOf(selectedcipher()) + encryptionkey.getText().toString();
    FileOutputStream fOut = null;
    OutputStreamWriter osw = null;

    try{
     fOut = openFileOutput("xorsettings.dat",MODE_PRIVATE);      
     osw = new OutputStreamWriter(fOut);
     osw.write(data);
     osw.flush();
     toasty("Settings saved.");
     }
     catch (Exception e) {      
     e.printStackTrace();
     toasty("Settings not saved.");
     }

     finally {
        try {
               osw.close();
               fOut.close();
               } catch (IOException e) {
               e.printStackTrace();
               }
     }
}


public void readcrypt(){
	final EditText encryptionkey =    (EditText) findViewById(R.id.encryptionkey);
    FileInputStream fIn = null;
    
    String data = null;
    StringBuilder total = new StringBuilder();
    String line;
    
    try{
     fIn = openFileInput("xorsettings.dat");      
     BufferedReader r = new BufferedReader(new InputStreamReader(fIn));
     while ((line = r.readLine()) != null) {
    	    total.append(line);
    	}
     data = total.toString();
     setcipher((int) data.charAt(0));
     encryptionkey.setText(data.substring(1));
     toasty("Settings successfully read.");
     }
     catch (Exception e) {      
     e.printStackTrace();
     toasty("Settings not read.");
     }    
}


protected void getContactInfo(Intent intent)
{	 String name;
	 String emailAddress;
	 String phoneNumber = "";
   Cursor cursor =  managedQuery(intent.getData(), null, null, null, null);  
   while (cursor.moveToNext()) 
   {           
	   final EditText txtphoneNo = (EditText) findViewById(R.id.txtphoneNo);
       String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
       name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); 

       String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

       if ( hasPhone.equalsIgnoreCase("1"))
           hasPhone = "true";
       else
           hasPhone = "false" ;

       if (Boolean.parseBoolean(hasPhone)) 
       {
        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
        while (phones.moveToNext()) 
        {
          phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
          txtphoneNo.setText(phoneNumber);
        }
        phones.close();
       }

       // Find Email Addresses
       Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId,null, null);
       while (emails.moveToNext()) 
       {
        emailAddress = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
       }
       emails.close();

  }  //while (cursor.moveToNext())        
   cursor.close();
}//getContactInfo



public void toasty(String toastmessage){
    Toast.makeText( getBaseContext(), toastmessage, Toast.LENGTH_SHORT).show();
	
}

public String deciphermessage(String key, String encmsg){ 
	final RadioButton ciphernone = (RadioButton) findViewById(R.id.ciphernone);
    final RadioButton cipherabc = (RadioButton) findViewById(R.id.cipherabc);
    final RadioButton cipherxor = (RadioButton) findViewById(R.id.cipherxor);
    final RadioButton cipherpass = (RadioButton) findViewById(R.id.cipherpass);
    final TextView readtext = (TextView) findViewById(R.id.readtext);
    
    String outstring = encmsg;
    
	if(cipherpass.isChecked()){         	  
      	try {
      		outstring = (decrypt(key,encmsg));} 
      	catch (Exception e) {
      		e.printStackTrace();
      	}}
  	else if(cipherabc.isChecked()){
  		outstring = (decryptabc(key, encmsg));
  	}
  	else if(cipherxor.isChecked()){
  		outstring = (XORdecryptstring(key,encmsg,1));
//  		outstring = "let's see if this works";
  	}
    else if(ciphernone.isChecked()){
      		outstring = (encmsg);
    }
    else{
    	outstring = (encmsg);
    };
	
    if(outstring=="")
    	outstring = encmsg;
    
	readtext.setText(outstring);
	return outstring;
};



public void visiblemenu(int theview){
	
    final TextView encryptedtext =    (TextView) findViewById(R.id.encryptedtext);
    final EditText encryptionkey =    (EditText) findViewById(R.id.encryptionkey);
    final EditText messagetoencrypt = (EditText) findViewById(R.id.messagetoencrypt);
    final TextView readtext = (TextView) findViewById(R.id.readtext);
    final EditText txtphoneNo = (EditText) findViewById(R.id.txtphoneNo);
    final RadioGroup cipherradio = (RadioGroup) findViewById(R.id.cipherradio);
    final TextView cipher01 = (TextView) findViewById(R.id.cipher01);
    final TextView send01 = (TextView) findViewById(R.id.send01);
    final TextView write01 = (TextView) findViewById(R.id.write01);
    final TextView send02 = (TextView) findViewById(R.id.send02);    
    final TextView read01 = (TextView) findViewById(R.id.read01);
    final Button previousmessage = (Button) findViewById(R.id.previousmessage);
    final Button refreshmessage = (Button) findViewById(R.id.refreshmessage);
    final Button nextmessage = (Button) findViewById(R.id.nextmessage);
    final Button btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
    final Button savekey = (Button) findViewById(R.id.savekey);
    final Button readkey = (Button) findViewById(R.id.readkey);
    
    
    cipher01.setVisibility(View.GONE);
    write01.setVisibility(View.GONE);
    send01.setVisibility(View.GONE);
    send02.setVisibility(View.GONE);
    read01.setVisibility(View.GONE);
    readtext.setVisibility(View.GONE);
    encryptedtext.setVisibility(View.GONE);
    encryptionkey.setVisibility(View.GONE);
    messagetoencrypt.setVisibility(View.GONE);
    txtphoneNo.setVisibility(View.GONE);
    btnSendSMS.setVisibility(View.GONE);
    previousmessage.setVisibility(View.GONE);
    refreshmessage.setVisibility(View.GONE);
    nextmessage.setVisibility(View.GONE);
    cipherradio.setVisibility(View.GONE);
    savekey.setVisibility(View.GONE);
    readkey.setVisibility(View.GONE);
   
    switch (theview)
    {
        case 1:  //write menu
            write01.setVisibility(View.VISIBLE);
            messagetoencrypt.setVisibility(View.VISIBLE);
            break;
        case 2:  //cipher menu
            cipher01.setVisibility(View.VISIBLE);
            encryptionkey.setVisibility(View.VISIBLE);
            cipherradio.setVisibility(View.VISIBLE);
            savekey.setVisibility(View.VISIBLE);
            readkey.setVisibility(View.VISIBLE);
            break;
        case 3:  //decrypt menu
            write01.setVisibility(View.VISIBLE);
            messagetoencrypt.setVisibility(View.VISIBLE);
            break;
        case 4:
            send01.setVisibility(View.VISIBLE);
            send02.setVisibility(View.VISIBLE);
            encryptedtext.setVisibility(View.VISIBLE);
            txtphoneNo.setVisibility(View.VISIBLE);
            btnSendSMS.setVisibility(View.VISIBLE);
        	break;
        case 5:
            read01.setVisibility(View.VISIBLE);
            readtext.setVisibility(View.VISIBLE);
            previousmessage.setVisibility(View.VISIBLE);
            refreshmessage.setVisibility(View.VISIBLE);
            nextmessage.setVisibility(View.VISIBLE);
        	break;
    }
 }

public static String toHex(String txt) {
    return toHex(txt.getBytes());
}
public static String fromHex(String hex) {
    return new String(toByte(hex));
}

public static byte[] toByte(String hexString) {
    int len = hexString.length()/2;
    byte[] result = new byte[len];
    for (int i = 0; i < len; i++)
            result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
    return result;
}

public static String toHex(byte[] buf) {
    if (buf == null)
            return "";
    StringBuffer result = new StringBuffer(2*buf.length);
    for (int i = 0; i < buf.length; i++) {
            appendHex(result, buf[i]);
    }
    return result.toString();
}
private final static String HEX = "0123456789ABCDEF";

private static void appendHex(StringBuffer sb, byte b) {
    sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
}
}
